package cloud

import (
	"errors"
	"smart_home/api/models"
	"smart_home/api/xfyun/depots"
)

type _cloudCache struct {
	// 是否开启处理程序
	//isOpenAfter bool
	cache map[string]struct {
		// 云函数处理  负责多轮对话
		cloud func(rq *depots.Request, res *depots.XfyunResult, userParams *UserParams)
		// 后处理函数 负责处理数据
		//after func(rq *depots.Request, res *depots.XfyunResult, userParams map[string]interface{})
	}
}

// json return struct
type ResultMsg struct {
	Code   int64       `json:"code"`
	Msg    string      `json:"msg"`
	Result interface{} `json:"result"`
}

type UserParams struct {
	User       *models.User `json:"user"`
	UserId     string       `json:"user_id"`
	Sta        string       `json:"sta"`
	DeviceType int          `json:"device_type"`
}

var cc = &_cloudCache{
	//isOpenAfter: true,
	cache: make(map[string]struct {
		cloud func(rq *depots.Request, res *depots.XfyunResult, userParams *UserParams)
		//after func(rq *depots.Request, res *depots.XfyunResult, userParams map[string]interface{})
	}),
}

func registerCloud(
	prefix string,
	cloud func(rq *depots.Request, res *depots.XfyunResult, userParams *UserParams),
	//after func(rq *depots.Request, res *depots.XfyunResult, userParams map[string]interface{}),
) error {
	if _, ok := cc.cache[prefix]; ok {
		return errors.New("after 已存在")
	}

	cc.cache[prefix] = struct {
		cloud func(rq *depots.Request, res *depots.XfyunResult, userParams *UserParams)
		//after func(rq *depots.Request, res *depots.XfyunResult, userParams map[string]interface{})
	}{cloud: cloud}

	return nil
}

func RunCloud(prefix string, rq *depots.Request, res *depots.XfyunResult, userParams *UserParams) error {
	if cache, ok := cc.cache[prefix]; ok {
		cache.cloud(rq, res, userParams)
		// 后处理
		//if cc.isOpenAfter && res.IsEnd && res.IsHandle {
		//cache.after(rq, res, userParams)
		//}
		return nil
	}
	return errors.New("cloud 不存在")
}
